package com.k.usbupdate.util

import android.content.Context
import android.os.storage.StorageManager
import java.io.File
import java.lang.reflect.Field
import java.lang.reflect.Method

object OTGUtil {

    val TAG = "OTGUtil"

    private const val classVolumeInfo = "android.os.storage.VolumeInfo" //反射使用的className
    private const val classDiskInfo = "android.os.storage.DiskInfo" //反射使用的className
    private val methodIsUsb = "isUsb"
    private val methodGetType = "getType"
    private val methodGetDisk = "getDisk"
    private val methodPath = "path"
    private val methodGetVolumes = "getVolumes"


    fun getUsbDir(context: Context): List<String> {
        var sdcardDir: String? = null
        val storageManager = context.getSystemService(Context.STORAGE_SERVICE) as StorageManager
        var volumeInfoClazz: Class<*>? = null
        var diskInfoClazz: Class<*>? = null
        var dataList = mutableListOf<String>()
        try {
            diskInfoClazz = Class.forName(classDiskInfo)
            val isUsb: Method = diskInfoClazz.getMethod(methodIsUsb)
            volumeInfoClazz = Class.forName(classVolumeInfo)
            val getType: Method = volumeInfoClazz.getMethod(methodGetType)
            val getDisk: Method = volumeInfoClazz.getMethod(methodGetDisk)
            val path: Field = volumeInfoClazz.getDeclaredField(methodPath)
            val getVolumes: Method = storageManager.javaClass.getMethod(methodGetVolumes)
            val result = getVolumes.invoke(storageManager) as List<Class<*>>
            for (i in result.indices) {
                val volumeInfo: Any = result[i]
                if (getType.invoke(volumeInfo) as Int == 0) {
                    val disk: Any = getDisk.invoke(volumeInfo)
                    if (disk != null) {
                        if (isUsb.invoke(disk) as Boolean) {
                            sdcardDir = path.get(volumeInfo) as String
                            dataList.add(sdcardDir)
                        }
                    }
                }
            }
            return dataList
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return dataList
    }

    fun findUpdateApkPaths(paths: List<String>): List<String> {
        val updateApkPaths = mutableListOf<String>()

        for (path in paths) {
            val apkPath = "$path/update.apk"
            val apkFile = File(apkPath)
            if (apkFile.exists()) {
                updateApkPaths.add(apkFile.absolutePath)
            }
        }

        return updateApkPaths
    }
}